package main;


import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.dom4j.DocumentException;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;

import com.jfinal.kit.StrKit;

import wordUtil.docExport.CustomXWPFDocument;
import wordUtil.docExport.PinyinUtils;

/**
 * 根据docx文件生成docx的导出模板
 */
public class MainExportDocxTemplate {

	public static Logger logger = Logger.getLogger(MainExportDocxTemplate.class);

	public static void main(String[] args) throws DocumentException, IOException {
		// docx模板导出
		genTemplate();
	}

	/**
	 * 生成docx模板
	 */
	private static void genTemplate() throws IOException {

		Class<MainExportDocxTemplate> clazz = MainExportDocxTemplate.class;
		URL resource = clazz.getResource("/国家电网公司变电检测通用管理规定 第1分册 红外热像检测细则—试用版.docx");

		String path = URLDecoder.decode(resource.getPath(), "UTF-8");

		CustomXWPFDocument doc = anasysWord(path);

		FileOutputStream fopts = new FileOutputStream("D://gen2.docx");

		try {
			doc.write(fopts);
		} finally {
			fopts.close();
		}

		System.out.println("ok!");
	}

	/**
	 * 解析模板
	 * 
	 * @param template
	 * @return
	 * @throws IOException
	 */
	public static CustomXWPFDocument anasysWord(String template) throws IOException {

		OPCPackage pack = POIXMLDocument.openPackage(template);
		CustomXWPFDocument doc = new CustomXWPFDocument(pack);

		// 处理表格
		Iterator<XWPFTable> it = doc.getTablesIterator();
		while (it.hasNext()) {
			XWPFTable table = it.next(); // 表

			List<XWPFTableRow> rows = table.getRows(); // 行
			for (int i = 0; i < rows.size(); i++) {
				XWPFTableRow row = rows.get(i);

				boolean rowisNull = fillAndCheck(row, i);
				// TODO 如果本行全不为空，则是分组数据，下一行需要被填充
				if (!rowisNull) {
					if (i + 1 < rows.size()) {
						fillFrom(row, rows.get(i + 1));
					}
				}
			}
		}
		// pack.close();
		return doc;
	}

	private static void fillFrom(XWPFTableRow fromRow, XWPFTableRow toRow) {

		List<XWPFTableCell> cells = fromRow.getTableCells(); // 每一行的所有列

		for (int j = 0; j < cells.size(); j++) { // 列

			XWPFTableCell cell = cells.get(j);

			// w:vmerge // 控制行合并,<w:vmerge w:val="restart" />,<w:vmerge w:val="continue" />
			// w:gridSpan // 控制列合并

			String text = cell.getText(); // 前一个字段的值
			if (StrKit.notBlank(text)) {
				List<XWPFTableCell> totableCells = toRow.getTableCells();
				if (totableCells.size() > j) {
					fill(totableCells.get(j), "key_" + PinyinUtils.getChinesePinYin(text));
				}
			}
		}
	}

	private static boolean fillAndCheck(XWPFTableRow row, int i) {
		boolean rowisNull = false;

		List<XWPFTableCell> cells = row.getTableCells(); // 每一行的所有列

		for (int j = 0; j < cells.size(); j++) { // 列

			XWPFTableCell cell = cells.get(j);

			// w:vmerge // 控制行合并,<w:vmerge w:val="restart" />,<w:vmerge w:val="continue" />
			// w:gridSpan // 控制列合并

			CTTcPr tcPr = cell.getCTTc().getTcPr();
			if (cells.size() == 1) {
				logger.info(String.format("****************** %s , 是否是合并行 :%s, 是否是合并列：%s, 行数据：%s", cell.getText(), tcPr.isSetVMerge() ? "是" : "否", tcPr.isSetGridSpan() ? "是" : "否", cell.getText()));
			} else {
				logger.info(String.format("第 %s 行  %s 列 = %s , 是否是合并行 :%s, 是否是合并列：%s, 行数据：%s", i, j, cell.getText(), tcPr.isSetVMerge() ? "是" : "否", tcPr.isSetGridSpan() ? "是" : "否", cell.getText()));
			}
			if (StrKit.isBlank(cell.getText()) && !tcPr.isSetVMerge()) {
				rowisNull = true;
			}
			if (j - 1 > -1) {
				String text = cells.get(j - 1).getText(); // 取前一个字段的值
				if (StrKit.notBlank(text)) {
					String pinyin = PinyinUtils.getChinesePinYin(text);
					fill(cell, pinyin);
				}
			}
		}
		if (!rowisNull) {
			logger.info("***************** 不为空 ");
		}
		return rowisNull;
	}

	/**
	 * 给cell填充值
	 * 
	 * @param cell
	 * @param text
	 */
	private static void fill(XWPFTableCell cell, String pinyin) {

		XWPFParagraph xwpfParagraph = cell.getParagraphs().get(0);

		List<XWPFRun> runs = xwpfParagraph.getRuns();
		if (runs.isEmpty() && StrKit.isBlank(cell.getText())) {
			XWPFRun createRun = xwpfParagraph.createRun();
			createRun.setFontSize(10);
			createRun.setText(pinyin, 0);
		}
	}
}
